package com.hindua.ailaaicuaai;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.hindua.tab.CategoryTab;
import com.hindua.tab.scr.CategoryScr;
import com.hindua.tab.scr.DangDocSrc;
import com.hindua.tab.scr.GioiThieuSrc;
import com.hindua.utils.DBAdapter;
import com.hindua.utils.IDatabaseHelper;
import com.hindua.utils.NetworkState;
import com.rtst.widget.actionbar.ActionBarActivity;
import com.rtst.widget.tab.ITabHost;
import com.rtst.widget.tab.SwipeyTabs;
import com.rtst.widget.tab.SwipeyTabsAdapter;
import com.rtst.widget.tab.TabFragment;
import com.hindua.beans.Item;
import com.hindua.ailaaicuaai.R;

public class MainActivity extends ActionBarActivity implements ITabHost, OnTabChangeListener, IDatabaseHelper {
	/** Called when the activity is first created. */
	private static final String TAG = "MainActivity";
	private volatile static MainActivity instance;
	private SwipeyTabs mTabs;
	private ViewPager mViewPager;
	public static final int EXIT_RESULT = 0x1;
	public static final String PEFERENCE_FILE = "pref_hindua_ailaaicuaai";
	public static final String CLIENT_VERSION = "MP_ANDROID_1.0.0";
	private DisplayMetrics disMetric = new DisplayMetrics();
    //public GoogleAnalyticsTracker mAnalyticsTracker;
    //public static final String GOOGLE_ANALYTICS = "UA-30468093-1";
    //public static final String HTTP_EXCEPTION_HANDLE_URL = "http://a.p.mana.vn/e/handle";
    public static final String HOST = "http://daudm.vietcntt.net/";
    private SharedPreferences settings;
	private SharedPreferences.Editor editor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		if (instance == null) instance = this;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_swipeytab);
		new NetworkState(MainActivity.this).check();
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
				getSupportFragmentManager());
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setCurrentItem(1);
		//ExceptionHandler.register(this, HTTP_EXCEPTION_HANDLE_URL);			// http://code.google.com/p/android-remote-stacktrace/
		//mAnalyticsTracker = GoogleAnalyticsTracker.getInstance();
		//mAnalyticsTracker.start(GOOGLE_ANALYTICS, 60, this);
		Toast.makeText(this, "Vui lòng click quảng cáo để ủng hộ tác giả bạn nhé ! ^_^", Toast.LENGTH_LONG).show();
	}
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.home, menu);

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			//Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show();
			break;
		case R.id.menu_market:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://search?q=pub%3AViet+Android+J.S.C&c=apps"));
			startActivity(intent);
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/*
	public void trackPageView(String page) {
		mAnalyticsTracker.trackPageView(page+"/"+getIMEI()+"/"+getCarrierName());
	} */

	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
			SwipeyTabsAdapter {

		private final String[] TITLES = { 
				"GIỚI THIỆU",
				"DANH MỤC",
				"ĐANG ĐỌC"
		};

		private final Context mContext;
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
			this.mContext = context;
		}

		@Override
		public Fragment getItem(int position) {
			Fragment fg = null;
			switch (position) {
			case 0:
				fg = new GioiThieuSrc();
				break;
			case 1:
				fg = new CategoryTab(CategoryScr.TYPE_HOME);
				break;
			case 2:
				fg = new DangDocSrc();
				break;
			default:
				
				break;
			}
			return fg;
		}

		@Override
		public int getCount() {
			return TITLES.length;
		}

		public ViewGroup getTab(final int position, SwipeyTabs root) {
			ViewGroup layout = (ViewGroup) LayoutInflater.from(mContext)
					.inflate(R.layout.swipey_tab_indicator, root, false);

			TextView view = (TextView) layout.findViewById(R.id.swipey_tab);
			view.setText(TITLES[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			return layout;
		}
	}
	

	@Override
	public int getContainerViewId() {
		return getTabContainerViewId(mViewPager.getCurrentItem());
	}

	@Override
	public int getTabContainerViewId(int id) {
		int containerId = 0;
		switch (id) {
		case 1:
			containerId = R.id.tab_category_container;
			break;
		}
		return containerId;
	}

	TabFragment mCurTabFragment;
	@Override
	public void setCurTabFragment(TabFragment fragment) {
		if(fragment == null) return;
		mCurTabFragment = fragment;
	}

	@Override
	public void onTabChanged(String tabId) {
		Log.i(TAG, "onTabChanged " + tabId);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
				&& keyCode == KeyEvent.KEYCODE_BACK
				&& event.getRepeatCount() == 0) {
			// Take care of calling this method on earlier versions of
			// the platform where it doesn't exist.
			onBackPressed();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
	    // This will be called either automatically for you on 2.0
	    // or later, or by the code above on earlier versions of the
	    // platform.
		if (mCurTabFragment != null) {
			mCurTabFragment.onBack();
		}
	    return;
	}
	
	public static MainActivity getInstance() {
		if (instance == null) {
			synchronized (MainActivity.class) {
				if (instance == null) {
					instance = new MainActivity();
				}
			}
		}
		return instance;
	}
	
	public String getCarrierName() {
		TelephonyManager manager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		String carrierName = manager.getNetworkOperatorName();
		return carrierName;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public String getIMEI() {
		TelephonyManager telephoneMgr = (TelephonyManager) getSystemService(getBaseContext().TELEPHONY_SERVICE);
		return telephoneMgr.getDeviceId();
	}

	/*
	@Override
	protected void onDestroy() {
		DBAdapter.getInstance(this).close();
		mAnalyticsTracker.stop();
		super.onDestroy();
	}
	*/
	
	@Override
	public DBAdapter getDBAdapter() {
		DBAdapter adapter = DBAdapter.getInstance(this);
		adapter.open();
		return adapter;
	}
	
	public int[] getDisplayDimension() {
		getWindowManager().getDefaultDisplay().getMetrics(disMetric);
		int[] dimension = new int[] { disMetric.widthPixels, disMetric.heightPixels };
		return dimension;
	}
	
	public String getDisplayDimensionStr() {
		int[] dimension = getDisplayDimension();
		return String.format("%dx%d", dimension[0], dimension[1]);
	}
	
	public void showMessageNoNetWork() {
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle("Chú ý");
		alertDialog.setMessage("Vui lòng kiểm tra lại mạng Wifi hoặc 3G");
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
			}
		});
		alertDialog.show();
	}	
	
	public void savePositionChapterBookmark(int pos) {
		this.settings = getSharedPreferences(PEFERENCE_FILE, 0);
		this.editor = this.settings.edit();
		if (pos >= 0) {
			editor.putInt("positionBookmark", pos);
			editor.commit();
		}
	}
	
	public int getPositionChapterBookmark() {
		this.settings = getSharedPreferences(PEFERENCE_FILE, 0);
		int pos = this.settings.getInt("positionBookmark", -1);
		return pos;
	}
}